﻿using System.Collections.Concurrent;
using WeDonekRpc.Client.Attr;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.Config;

namespace Shop.ExtendService.Config
{
    [ClassLifetimeAttr(ClassLifetimeType.SingleInstance)]
    internal class DictConfig : IDictConfig
    {
        private readonly ConcurrentDictionary<string, long> _DictCache = new ConcurrentDictionary<string, long>();
        private readonly IConfigSection _Section;
        public DictConfig ( IConfigCollect server )
        {
            this._Section = server.GetSection("Shop:Dict");
            this._Section.AddRefreshEvent(this._Refresh);
        }

        private void _Refresh ( IConfigSection section, string name )
        {
            if ( name.IsNull() )
            {
                return;
            }
            _ = this._DictCache.TryRemove(name, out _);
        }

        public long GetDictId ( string key )
        {
            if ( this._DictCache.TryGetValue(key, out long id) )
            {
                return id;
            }
            id = this._Section.GetValue<long>(key);
            _ = this._DictCache.TryAdd(key, id);
            return id;
        }
    }
}
